package pt.iscte.pcd.ballmovers;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.swing.JFrame;


public class BallMoversApp {
	
	private static final int MAX_COLOR = 256;
	private static final int MAX_Y_FRAME = 488;
	private static final int MAX_X_FRAME = 416;
	private static final int MAX_Y = 400;
	private static final int MAX_X = 400;
	
	protected static final int MAX_THREADS = 1000;
	
	public static final int END_OF_TRACK = 380;
	private static final int MAX_EXECUTING_THREADS = 100;
	
	private JFrame frame;
	private ExecutorService pool;
	private boolean done;
	private BallDrawer drawer;
	private Ball[] balls = new Ball[MAX_THREADS];;

	public BallMoversApp() {
		
		frame = new JFrame("Ballmovers");
		frame.setLayout(new BorderLayout());
		Button start = new Button("Start");
		frame.add(start, BorderLayout.NORTH);
		Button end = new Button("End");
		frame.add(end, BorderLayout.SOUTH);
		frame.setSize(new Dimension(MAX_X_FRAME, MAX_Y_FRAME));
		Container c = frame.getContentPane();
		drawer = new BallDrawer();
		c.add(drawer);
		
		start.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				for (int i = 0; i != MAX_THREADS; i++) {					
					pool.execute(new BallMover(i, balls[i], drawer));
				}
			}			
		});
		
		end.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				done = true;
				pool.shutdownNow();
				frame.dispose();
			}			
		});
		
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		pool = Executors.newFixedThreadPool(MAX_EXECUTING_THREADS);
		
		System.out.println("Ending Ball Movers App Constructor");
		
	}
	
	public void execute() {
		System.out.println("Starting Ball Movers App execution");
		Random gen = new Random();
		for (int i = 0; i != MAX_THREADS; i++) {
			Ball ball = new Ball(gen.nextInt(MAX_Y), new Color(gen.nextInt()));
			drawer.add(ball);
			balls [i] = ball;
		}
		frame.setVisible(true);
		System.out.println("All threads created and executing");
		System.out.println("Window size is: " + frame.getSize());
		System.out.println("Window size is: " + frame.getContentPane().getSize());
	}

}
